if(window.jQuery && window.jQuery.PPF && !window.$PPF.shijuan) {
	(function($){
		$PPF.extend({
			shijuan: {
				//检查
				id: 0,
				odata: {},
				data : {},
				data2 : {},
				ddata: {},
				sdata: {},
				gdata: {},
				dlnum: {},
				stype: {},
				tjson: {},
				testpassed: null,
				initdata : function(d){
					if(typeof d !== "object" || !d ) return;
					for(var e in d) {
						//export to data && data2 && set input val;
						if(e=='id') {
							this.setid(d[e]);
							$("input[name='id']").val(d[e]);
						}else if( /^(title|dotime|limittime|class|d_descrip|d_overdescrip|money|jnum|jrate|ktimes|okrate|d_helplink|d_dostyle|mtype|jmtype|type|pagesize)$/.test(e) ){	//data input!
							this.data[e]=d[e];
							$(":input[name='" + e + "']").val(d[e]);
						}else if( /^(okban|selfpf|cjopen|phopen|open)$/.test(e) ){	//data checkbox
							this.data[e]=d[e];
							$("input[name='" + e + "'][value='" + d[e] + "']").attr('checked','checked');
						}else if( /^(d_allowgroups|d_allowbids|d_allowcolleges|d_allowgrades|d_allowpros|d_allowclasses|d_alloweclasses)$/.test(e) ){
							if(typeof d[e] == "object" && d[e]){
								this.data[e] = d[e];
								//click
								for(var i in d[e]){
									var o = $("input[type='checkbox'][name='"+e+"'][value='"+d[e][i]+"']")
									if( !o.attr('checked') ) o.get(0).click();
								}
							}else {
								this.data[e]=[];
								var o = $("input[type='checkbox'][name='"+e+"'][value='0']");
								if( !o.attr('checked') ) o.get(0).click();
							}
						}else if( /^protected$/.test(e) ) {	//data radio
							this.data[e]=d[e];
							$("input[name='" + e + "'][value='" + d[e] + "']").attr('checked','checked');
						}else if(e == 'start_string'){
							this.data.start=d[e];
							$(":input[name='start']").val(d[e]);
						}else if(e == 'end_string'){
							this.data.end=d[e];
							$(":input[name='end']").val(d[e]);
						}else if(e == 'd_dlmix' && d[e]){
							this.initduan(d[e]);
							delete this.data[e];
						}else if(e == 'd_xtmix' && d[e]){
							this.sdata=d[e];
						}else if('dlnum' == e){
							this.dlnum = d[e];
						}
						else {	//to do data2 选题信息
							this.data2[e]=d[e];
						}
					}
					this.getdata();
					this.copyodata();
					this.updatesui();
					this.updategu();
				},
				copyodata: function(){
					this.odata = $.extend( true , {} , this.data );
				},
				setid: function(id) {
					this.id = this.data['id'] = this.data2['id'] = id;
				},
				check : function(i){
					switch(i){
						case 1:
							return $PPF.validate.check( $("[ppf='shijuan']",$("#_sjedit_1")),3);
						case 2:
							this.getdata();
							return true;
						case 3:
							return true;
							return $PPF.validate.check( $("[ppf='shijuan']",$("#_sjedit_3")),3);
						case 4:
							return true;
							var r = $PPF.validate.check( $("[ppf='shijuan']",$("#_sjedit_4")),3);
							//if(r) this.getdata(1);
							return r;
					}
				},
				getdata: function() {	//从表单获得变量
					var _t = this;
					$("[ppf='shijuan']").each(function(i){
						var o=$(this);
						var n=o.attr('name');
						if( /^(title|start|end|dotime|class|limittime|d_descrip|d_overdescrip|money|jnum|jrate|ktimes|okrate|d_helplink|d_dostyle|pagesize)$/.test(n) ){
							_t.data[n] = o.val();
						}else if( /^(okban|selfpf|cjopen|phopen)$/.test(n) ){
							_t.data[n] = o.attr('checked') ? 1 : 0
						}else if( /^protected$/.test(n) ) {
							if(o.attr('checked')) {
								_t.data[n] = o.val();
							}
						}else if( /^(mtype|jmtype|type)$/.test(n) ) {
							_t.data[n] = o.val();
						}
					});
					var tree = ["d_allowgroups","d_allowbids","d_allowcolleges","d_allowgrades","d_allowpros","d_allowclasses","d_alloweclasses"];
					for(n=0;n<tree.length;n++) {
						_t.data[tree[n]] = [];
						$("input[name='" + tree[n] + "']").each(function(i){
							var o=$(this);
							if(o.attr('checked')){
								if( !o.val() || o.val().toString() == '0' ){
									_t.data[tree[n]]=[];
									return false;
								}else {
									_t.data[tree[n]][_t.data[tree[n]].length] = o.val();
								}
							}
						});
					}
				},
				go: function(i) {
					// i 1、2、3、4
					if(i==2) {	//go 2
						if(this.check(1)) this.show(2);
					}else if(i==3){	//save12 & go 3
						if(this.check(1)){ if(this.check(2)) this.save() }else this.show(1);
					}else if(i==4){	//go 4
						//if(this.check(3)) this.show(4);
						this.show(4);
					}else if(i==5){	//submit
						//if(this.check(3)){ if(this.check(4)) this.save2() }else this.show(3);
						this.save2();
					}else{
						this.show(1);
					}
				},
				show: function(t) {
					if(t >=1 && t<=4){
						$("div[id^='_sjedit_']").hide();
						$("#_sjedit_"+t).show();
					}else{
						$("div[id^='_sjedit_']").hide();
						$("#_sjedit_1").show();
					}
				},
				//保存
				save: function(callback){	//save 1
					var query = {};
					var _t = this;
					query = PPF.param(this.data);
					query.inajax = 1;
					if( !PPF.compObject(this.data,this.odata)) {
						$PPF.tips( {msg: "保存中"} );	//保存中
						if(typeof callback === "undefined") {
							callback = function(data){
								$PPF.tips( {msg: $PPF.jsonmsg(data,"保存成功") , timeout:3000} );
								_t.show(3);
							}
						}
						var _t = this;
						var _cb = function(data){
							callback(data);
							_t.setid(data.id);
							_t.copyodata();
						}
						$.post(__System.roots.exam + "manage_shijuan/save",query,_cb,'json');
					}else {
						this.show(3);
					}
				},
				dialog: {
					addduan: function(){
						PPF.dialog( {title:"添加试卷段落" , msg: $('#editduan_tpl').content({
								t: '',d: '',did:0,st: 0,ed: 0
							}), type:2 , callback:function(){return PPF.shijuan.addduan(0)} });
					},
					editduan: function(did){
						PPF.dialog( {title:"编辑试卷段落" , msg: $('#editduan_tpl').content({
							t: PPF.shijuan.ddata[did].t,d: PPF.shijuan.ddata[did].d,did: did,st: PPF.shijuan.ddata[did].st,ed: PPF.shijuan.ddata[did].ed
						}) , type:2 , callback:function(){return PPF.shijuan.addduan(did)} });
					},
					delduan: function(did) {
						PPF.dialog({title:"删除试卷段落" , msg:"确定删除？不可恢复！" , type:2 , callback: function(){return PPF.shijuan.delduan(did)} });
					},
					delsui: function(xid) {
						PPF.dialog({
							title:"删除随机选题", msg: "确定删除？", xid:xid , type:2, callback: function(){return PPF.shijuan.delsui(xid)}
						});
					},
					selectshiti: function(did) {
						var url = __System.roots.exam + "manage_shijuan/selectshiti/sjid/"+PPF.shijuan.id + "/did/"+did+"?_="+ +new Date();
						PPF.dialog( {title:"选择试题（固定选题）" , iframe: url , type: 0 , width: 800} );
					},
					selectsui: function(did) {
						PPF.dialog( {title:"选择试题（随机选题）" , msg: $("#selectsui_tpl").content({
								num: 0, fen: 1, kf: 0, hfen: 0, lvlmin:0, lvlmax: 0,did: did,xid: 0
							}) , type: 2, width: 600, callback:function(){return PPF.shijuan.addsui(did)} });
						$("[key='fen'],[key='kf'],[key='hfen']",$("#selectsui")).hide();
					},
					editsui: function(id) {
						var d = PPF.shijuan.sdata[id];
						PPF.dialog( {title:"选择试题（随机选题）" , msg: $("#selectsui_tpl").content({
								num: d.num, fen: d.fen ?d.fen:0, kf: d.kf?d.kf:0, hfen: d.hf?d.hf:0, lvlmin:d.lvlmin?d.lvlmin:0, lvlmax: d.lvlmax?d.lvlmax:0,did: d.did,xid: d.xid
							}) , type: 2, width: 600, callback:function(){return PPF.shijuan.addsui(d.did)} });
						$("[name='type']","#selectsui").val(d.type).change();
						$("[name='tiku']","#selectsui").val(d.tiku);
					},
					shitiedit: function(did) {
						var url = __System.roots.exam + "manage_shijuan/shitiedit/sjid/"+PPF.shijuan.id + "/did/"+did+"?_="+ +new Date();
						PPF.dialog( {title:"编辑固定选题" , iframe: url , type: 0 , width: 800 , height: 500 } );
					}
				},
				addsui: function(did){
					if($PPF.validate.check( $("[ppf='suiji']:visible",$("#selectsui")),3)){
						var p = {did:did};
						$("[ppf='suiji']").each(function(){
							var n = $(this).attr('name');
								p[n] = $(this).val();
						});
						p.inajax = 1;
						var url = __System.roots.exam + "manage_shijuan/selectsui/sjid/" + this.id;
						//$(":input[ppf='url'][name='t_selectsui']").val();
						$.post(url,p,function(data){
							if( data._code == 0 ){
								PPF.tips( {msg: PPF.jsonmsg(data,"操作成功") , timeout:1000} );
								PPF.shijuan.recordsui(data);
								PPF.shijuan.appendsui(data);
							}else{
								PPF.dialog( {msg: PPF.jsonmsg(data,"操作失败"),title: "提示信息"});
								return 'keep';
							}
						},'json');
					}else {
						return 'keep';
					}
				},
				delsui: function(xid) {
					var url = __System.roots.exam + "manage_shijuan/delsui";
					p = {xid:xid,sjid:this.id,inajax:1};
					var _t = this;
					$.post(url,p,function(data){
						if(data._code == 0){
							PPF.tips( {msg: PPF.jsonmsg(data,"操作成功") , timeout:1000} );
							delete PPF.shijuan.sdata[xid];
							$("table[key='_xid_"+xid+"']").remove();
							_t.testpassed = null;
						}else{
							PPF.dialog( {msg: PPF.jsonmsg(data,"操作失败"),title: "提示信息"});
							return 'keep';
						}
					},'json');
				},
				addduan: function(did){
					var d = $("#duanedit");
					if(PPF.validate.check( $("[ppf='duan']",d),3)){
						//$("input[name='id']").val()
						var p = {id: this.id, t: $("[name='t']",d).val(), d: $("[name='d']",d).val() , did:did ,st:$("[name='start']",d).val() , ed:$("[name='end']",d).val() , inajax : 1 };
						var url = __System.roots.exam + "manage_shijuan/duan";
						//$(":input[ppf='url'][name='t_addduan']").val();
						$.post(url,p,function(data){
							if(data._code == 0) {
								PPF.tips( {msg: PPF.jsonmsg(data,"操作成功") , timeout:1000} );
								PPF.shijuan.recordduan(data);
								PPF.shijuan.appendduan(data);
								PPF.shijuan.updatesui();
								PPF.shijuan.updategu();
							}else {
								PPF.dialog( {msg: PPF.jsonmsg(data,"操作失败"),title: "提示信息"});
								return 'keep';
							}
						},'json');
					}else {
						return 'keep';
					}
				},
				appendduan: function(d,did){
					var id = did || d.did;
					var tpl= $('#duan_tpl').content({
						t:d.t,
						d:d.d,
						id:id,
						st:'',
						ed:''
					});//增加
					if($("#_duan_"+id).size()>0) {
						$("#_duan_"+id).replaceWith(tpl);
					}else {
						$("#_xuanti").append(tpl);
					}
				},
				appendsui: function(d,xid){
					d.stype=this.stype[d.type].name;
					d.tikuname = typeof this.tjson[d.tiku] != "undefined" ? this.tjson[d.tiku].name : "undefined";
					d.xid = d.xid || xid;
					d.fen = PPF.formatFen(d.fen);
					var s = $("#suiji_tpl").content(d);
					var q=$(s);
					switch(this.stype[d.type].tixing){
						case "danxuan":
							$("[tag='hfen']",q).remove();
						break;
						case "duoxuan":
						break;
						case "xinli":
							$("[tag='hfen']",q).remove();
							$("[tag='fen']",q).remove();
							$("[tag='kf']",q).remove();
						break;
						case "jianda":
							$("[tag='hfen']",q).remove();
							$("[tag='kf']",q).remove();
						break;
					}
					if($("table[key='_xid_"+d.xid+"']").size())
						$("table[key='_xid_"+d.xid+"']").replaceWith(q);
					else
						$("div._c",$("#_suiji_"+d.did)).append(q);
					this.testpassed = null;
				},
				delduan: function(did){
					var url = __System.roots.exam + "manage_shijuan/duan/a/del";
					p = {did:did,id:this.id,inajax:1};
					$.post(url,p,function(data){
						if(data._code == 0) {
								PPF.tips( {msg: PPF.jsonmsg(data,"操作成功") , timeout:1000} );
								delete PPF.shijuan.ddata[did];
								$("#_duan_"+did).remove();
							}else {
								PPF.dialog( {msg: PPF.jsonmsg(data,"操作失败"),title: "提示信息"} );
								PPF.tips.remove();
							}
					},'json');
				},
				updategu: function() {	//更新固定选题
					for(var e in this.dlnum){
						var n = this.dlnum[e];
						if(n)
							$("div._c",$("#_shiti_"+e)).html("已选择 " + n + " 题，<a href=\"javascript:;\" onclick=\"PPF.shijuan.dialog.shitiedit(" + e + ")\">点击编辑</a> <a href=\"javascript:;\" onclick=\"PPF.shijuan.dialog.selectshiti(" + e + ")\">继续选题</a>");
					}
				},
				updatesui: function(){	//更新随机选题
					$("div._c",$("div[id^='_suiji_']")).empty();
					for(var e in this.sdata){
						this.appendsui(this.sdata[e],e);
					}
				},
				initduan: function(d) {
					for(var e in d) {
						d[e].did = e;
						this.appendduan(d[e]);
					}
					this.ddata = d;
				},
				recordduan: function(d){	//记录段信息
					this.ddata[d.did] = d;	//存储
				},
				recordsui: function(d){		//记录随机选题信息
					this.sdata[d.xid] = d;
				},
				recordgu: function(d){		//记录固定选题信息
					this.gdata[d.id] = d;
				},
				showclasses: function(){
					PPF.dialog({title:'选择分类',msg: $($('#class_tpl').content()).ptree() , type:0});
				},
				selectclass: function(o,noset){
					var v = PPF.ptreeselect(o,$($('#class_tpl').content()),"#selectclass");
					if(!noset){
						$("input[name='class']").val( v );
						this.data['class'] = v;
					}
					PPF.dialog.close();
				},
				open: function(callback) {	//save 2
					var _t = this;
					var op = $("input[name='open']").attr('checked') ? 1 : 0;
					if(op != this.data.open) {
						var query = {op:op,sjid:this.id,inajax:1};
						$PPF.tips( {msg: "保存中"} );	//保存中
						if(typeof callback === "undefined") {
							callback = function(data){
								$PPF.tips( {msg: $PPF.jsonmsg(data,"保存成功") , timeout:3000} );
							}
						}
						var _cb = function(data){
							callback(data);
							_t.data.open=op;
						}
						$.post(__System.roots.exam + "manage_shijuan/open",query,_cb,'json');
					}else {
						$PPF.tips( {msg: "保存成功" , timeout:3000} );
					}
				},
				test: function(i){
					i = i || 1;
					var _t = this;
					if(i == 0) PPF.tips( {msg: "开始测试" , timeout:2000} );
					$.post(__System.roots.exam + "manage_shijuan/selecttest",{sjid:this.id,index:i,inajax:1},function(data){
						if(data._code != 0){
							PPF.tips( {msg:PPF.jsonmsg(data,"测试失败"),timeout:1000,type:1} );
							return;
						}
						PPF.tips( {msg: "第"+data.index+"轮测试完成" , timeout:1000} );
						var ta = ['第' + data.index + '轮测试开始：'];
						for(var e in data.trace){
							var s = '';
							s += "测试从题库<strong>" + _t.tjson[ _t.sdata[e].tiku ].name + "</strong>选择" + data.trace[e].need + "题<strong>" + _t.stype[ _t.sdata[e].type ].name + "</strong><br />";
							s += "选得:" + data.trace[e].num + "题<br />";
							if(data.trace[e].need == data.trace[e].num) {
								s += "<span class=\"green\">测试通过</span>";
							}else{
								s += "<span class=\"red\">测试不通过</span>";
								$("table[key='_xid_"+e+"']").addClass("red");
							}
							ta[ta.length] = s;
						}
						if(data.result) ta[ta.length] = "<span class=\"green\">本轮测试通过</span>";
						else ta[ta.length] = "<span class=\"red\">本轮测试不通过</span><a href=\"javascript:;\" onclick=\"gostep(3);\">返回修改</a>";
						ta[ta.length] = "<br />";
						$("#_sjtest_"+data.index).html( ta.join("<br />") );
						if(true !== _t.testpassed && false !== _t.testpassed) _t.testpassed = true;
						_t.testpassed = !!(_t.testpassed && data.result);
						if(i < 4) _t.test( ++i );
					},'json');
				},opentest: function(o){
					if($(o).attr("checked")) {
						if(true !== this.testpassed){
							PPF.dialog( {title:"确定开放？" , msg: "您还没有通过选题测试，确定开放测试？", type:2 , oncancel: function(){ $(o).removeAttr("checked") } });
						}
					}
				}
			}
			//to add!
		});
	})(jQuery);
	
	function changeType(){
		var type = $("select option:selected",$("#selectsui")).parent().attr("key");
		$("[key='fen'],[key='kf'],[key='hfen']").hide();
		switch(type){
			case "danxuan":
				$("[key='fen'],[key='kf']").show();
				break;
			case "duoxuan":
				$("[key='fen'],[key='kf'],[key='hfen']").show();
				break;
			case "jianda":
				$("[key='fen']").show();
				break;
			case "xinli":
				break;
		}
	}
}